package models

import (
	"ginstudydemo.com/main/dao"
	"strconv"
	"strings"
)

// GetDept 根据 关键词和状态 获取部门列表
func GetDept(query GetDeptQuery) (*[]GetDeptRes, error) {
	var results []GetDeptRes

	//SELECT id, name, code, parent_id, tree_path, sort, status, create_by, update_by, create_time, update_time, is_deleted FROM sys_dept WHERE is_deleted = 0 AND id IN (SELECT id FROM sys_dept WHERE id = 1 OR FIND_IN_SET(1, tree_path)) ORDER BY sort ASC

	model := dao.Db.Debug().Table("sys_dept t1").
		Select("id, name, code, parent_id, tree_path, sort, status, create_by, update_by, create_time, update_time, is_deleted").
		Where("is_deleted = 0").
		Order("sort ASC")

	// 如果传入了查询条件，则加入模糊查询
	if query.Keywords != "" {
		model = model.Where("name LIKE ? ", "%"+query.Keywords+"%")
	}

	if query.Status != "" {
		model = model.Where("status = ? ", query.Status)
	}

	if err := model.Scan(&results).Error; err != nil {
		return nil, err
	}

	return &results, nil

}

// GetDeptOptions 获取部门下拉
func GetDeptOptions() (*[]GetDeptOptionsRes, error) {
	var results []GetDeptOptionsRes

	model := dao.Db.Debug().Table("sys_dept t1").
		Select("id, name, code, parent_id, tree_path, sort, status, create_by, update_by, create_time, update_time, is_deleted").
		Order("sort ASC")

	if err := model.Scan(&results).Error; err != nil {
		return nil, err
	}

	return &results, nil

}

// GetDeptInfoById 根据 id 获取部门数据
func GetDeptInfoById(id string) (*DeptFormData, error) {

	var result DeptFormData

	err := dao.Db.Debug().Table("sys_dept").
		Select("id, name, code, parent_id, tree_path, sort, status, create_by, update_by, create_time, update_time, is_deleted").
		Where("id = ?", id).
		Scan(&result).Error

	if err != nil {
		return nil, err
	}
	return &result, nil

}

// AddDept 新增部门
func AddDept(insertData AddDeptBody) (int64, error) {

	err := dao.Db.Table("sys_dept").Create(&insertData).Error // 通过数据的指针来创建
	return insertData.ID, err
}

// EditDept 修改部门
func EditDept(menus AddDeptBody, menuId string) error {

	err := dao.Db.Debug().Table("sys_dept").
		Where("id = ?", menuId).
		Updates(&menus).Error

	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
	return err
}

// DelDept 批量删除部门（硬删除）
func DelDept(ids string) error {

	var idsArr []SysUserId
	for _, val := range strings.Split(ids, ",") {
		valNew, _ := strconv.ParseInt(val, 10, 64)
		idsArr = append(idsArr, SysUserId{
			ID: valNew,
		})
	}
	err := dao.Db.Debug().Table("sys_dept").Delete(&idsArr).Error
	return err
}
